package com.atguigu.gmall.web.controller;

import com.atguigu.gmall.cart.client.FeignCartClient;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.product.SkuInfo;
import com.atguigu.gmall.product.client.ProductClientFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author BrookPeng
 * @Date 2020/12/3 16:54
 * @Version 1.0
 */
@Controller
public class CartController {

    @Autowired
    private FeignCartClient feignCartClient;

    @Autowired
    private ProductClientFeign productClientFeign;

    // 加入购物车
    // http://cart.gmall.com/toCart?skuId=15&skuNum=1
    @GetMapping("/addCart.html")
    public String addCart(
            Long skuId,
            Integer skuNum,
            HttpServletRequest request,
            RedirectAttributes redirectAttributes)
    {

//        String userId = AuthContextHolder.getUserId(request);
//        String userTempId = AuthContextHolder.getUserTempId(request);
//        System.out.println("userId = " + userId);
//        System.out.println("userTempId = " + userTempId);

        feignCartClient.addCart(skuId, skuNum);

        redirectAttributes.addAttribute("skuId", skuId);
        redirectAttributes.addAttribute("skuNum", skuNum);

        // 回显添加商品成功页面
        // return "redirect:http://cart.gmall.com/toCart?skuId=" + skuId + "&skuNum=" + skuNum;
        // return "redirect:/toCart?skuId=" + skuId + "&skuNum=" + skuNum;
        return "redirect:http://cart.gmall.com/toCart";
    }

    // 回显购物车页面(添加了商品)
    @GetMapping("/toCart")
    public String toCart(
            Long skuId,
            Integer skuNum,
            HttpServletRequest request
    ) {

        // 查询商品实时价格(远程调用商品微服务)
        SkuInfo skuInfo = productClientFeign.getSkuInfo(skuId);
        CartInfo cartInfo = new CartInfo();
        cartInfo.setSkuId(skuId);
        cartInfo.setSkuName(skuInfo.getSkuName());
        cartInfo.setSkuNum(skuNum);
        cartInfo.setImgUrl(skuInfo.getSkuDefaultImg());
        request.setAttribute("cartInfo", cartInfo);

        // 回显添加商品成功页面
        return "cart/addCart.html";
    }

    // 去购物车结算
    @GetMapping("/cart.html")
    public String cart() {

        // 购物车页面
        return "cart/index";
    }
}